package springboot.service;

import springboot.Interface.serviceInterface.UserServiceInterface;
import springboot.dao.PermissionDao;
import springboot.dao.RoleDao;
import springboot.dao.RolePermissionDao;
import springboot.dao.UserDao;
import springboot.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class UserService implements UserServiceInterface {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;
    @Autowired
    private PermissionDao permissionDao;

    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public String addUser(User user) {
        if(userDao.addUser(user)){
            return "添加成功";
        }else {
            return "添加失败";
        }
    }
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public List<User> getUsers() {
        List<User> users = userDao.getUsers();
        if (users.size()==0){
            return null;
        }
        return users;
    }
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public User getUserById(int id) {
        return userDao.getUserById(id);
    }
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public String getNameById(int id) {
        return userDao.getUsernameById(id);
    }
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public String updateUser(int id, User user) {
        if (userDao.updateUserById(id,user)){
            return "修改成功";
        }
        return "修改失败";
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public String deleteUserById(int id) {

        if (userDao.deleteUserById(id)){
            return "删除成功";
        }
        return "删除失败";
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public User findByUserName(String name) {
        User user = userDao.getUserByName(name);
        if(user == null){
            return null;
        }else {
            user.setRole(roleDao.getRolesById(user.getRole().getId()));
            List<Integer> pIds = rolePermissionDao.getPermissionByRoleId(user.getRole().getId());
            if (pIds != null && pIds.size() > 0) {
                user.getRole().setPermissions(permissionDao.getPermissionsByIds(pIds));
            }
            return user;
        }
    }
}
